<template>
  <div class="department">
    <eHeader @doSearch="doSearch" />
    <div class="table-buttons-box">
      <div class="table-option-buttons">
        <el-button
          v-btnPermission:add
          icon="el-icon-plus"
          type="primary"
          @click="switchHandle('add')"
        >{{ $t("add") }}</el-button>
        <el-button
          v-btnPermission:edit
          :disabled="UpdateDisabled"
          type="primary"
          icon="el-icon-edit"
          @click="switchHandle('modify')">{{ $t("modify") }}</el-button>
        <el-button
          v-btnPermission:delete
          :disabled="DeleteDisabled"
          type="danger"
          icon="el-icon-delete"
          @click="switchHandle('del')">{{ $t("delete") }}</el-button>
        <el-button
          v-btnPermission:lend
          type="primary"
          icon="el-icon-s-check"
          @click="openLend">{{ $t("lend") }}</el-button>
        <el-button
          v-btnPermission:return
          type="primary"
          icon="el-icon-s-check"
          @click="returnEqp">{{ $t("return") }}</el-button>
        <el-button
          v-btnPermission:maintain
          type="primary"
          icon="el-icon-brush"
          @click="maintain"
        >{{ $t("maintain") }}</el-button
        >
        <el-button
          v-btnPermission:sendBack
          :disabled="DeleteDisabled"
          type="primary"
          icon="el-icon-top-right"
          @click="doSendBack"
        >{{ $t("SendBack") }}</el-button
        >
        <el-button
          v-btnPermission:enterWarehouse
          type="primary"
          icon="el-icon-plus"
          @click="oprnWareHousing($t('enterWarehouse'), 'in')"
        >{{ $t("enterWarehouse") }}</el-button
        >
        <el-button
          v-btnPermission:scrap
          type="primary"
          icon="el-icon-minus"
          @click="oprnWareHousing($t('ScrapTooling'), 'out')"
        >{{ $t("ScrapTooling") }}</el-button
        >
        <el-button
          v-btnPermission:onBoard
          type="primary"
          icon="el-icon-upload2"
          @click="toolingOn"
        >{{ $t('onBoard') }}</el-button
        >
        <el-button
          v-btnPermission:disembark
          type="primary"
          icon="el-icon-download"
          @click="toolingOff"
        >{{ $t('Disembark') }}</el-button>
      </div>
      <div class="table-option-buttons">
        <el-button
          v-btnPermission:add
          type="primary"
          icon="el-icon-download"
          @click="switchHandle('download')"
        >{{ $t("downloadTemp") }}</el-button
        >
        <el-upload
          :action="baseApi + '/mtms/upload/submit?name=ToolingBaseList'"
          :headers="headers"
          :show-file-list="false"
          :on-success="uploadSuccess"
          :on-error="importFail"
          class="upload-btn"
          style="display: inline-block"
          accept=".xlsx"
        >
          <el-button
            v-btnPermission:add
            type="primary"
            icon="el-icon-upload"
          >{{ $t("import") }}</el-button
          >
        </el-upload>
        <el-button
          v-btnPermission:add
          :style="{marginTop: '10px'}"
          type="primary"
          icon="el-icon-download"
          @click="switchHandle('export')"
        >{{ $t("export") }}</el-button>
      </div>
    </div>
    <!-- 主体部分 -->
    <el-card class="box-card" shadow="never">
      <!-- 表单部分 -->
      <el-row>
        <dynTable
          ref="dynTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-columns="tableColumns"
          :handle-selection-change="handleSelectionChange"
          :row-click="rowClick"
        />
      </el-row>
      <!--分页组件-->
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="getList"
      />
    </el-card>
    <!--表单渲染-->
    <!-- <eForm :job-status="this.job_status" /> -->
    <!-- 新增编辑组件 -->
    <myDialog
      ref="myDialog"
      :title="title"
      :is-disabled="isDisabled"
      @initList="initList"
      @closeDialog="closeDialog"
    />
    <!-- 借用弹窗组件 -->
    <lendDialog ref="lendDialog" @initList="initList" />
    <!-- 归还弹窗组件 -->
    <returnEqpDialog ref="returnEqpDialog" @initList="initList" />
    <!-- 入库弹窗组件 -->
    <wareHousing ref="wareHousingDialog" @initList="initList" />
    <!-- 修改记录组件? 差点没找到 -->
    <changeHistory ref="changeHistoryDialog" />
    <!-- 维护组件 -->
    <maintainDialog ref="maintainDialog" @initList="initList" />
    <toolingOnModel ref="toolingOnModel" @initList="initList"/>
    <toolingOffModel ref="toolingOffModel" @initList="initList"/>
  </div>
</template>

<script>
import crudJob from '@/api/Tooling/toolingBasicInfo'
import changeHistory from '../../components/changeHistory'
import mySetting from '@/mixins/mySetting'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
const ToolingFlag = [
  'Free',
  'Lend',
  'Lock',
  'PM',
  'Occupy', // 占用
  'Repairs', // 报修
  'Defect',
  'SendBack']
export default {
  name: 'ToolingBasePage',
  components: {
    eHeader: () => import(/* webpackChunkName: "eHeader" */ './module/header.vue'),
    myDialog: () => import(/* webpackChunkName: "myDialog" */ './module/form.vue'),
    wareHousing: () => import(/* webpackChunkName: "wareHousing" */ './module/wareHousing.vue'),
    maintainDialog: () => import(/* webpackChunkName: "maintainDialog" */ './module/maintainDialog.vue'),
    lendDialog: () => import(/* webpackChunkName: "lendDialog" */ './module/lendDialog.vue'),
    returnEqpDialog: () => import(/* webpackChunkName: "returnEqpDialog" */ './module/returnEqp.vue'),
    toolingOnModel: () => import(/* webpackChunkName: "returnEqpDialog" */ './module/toolingOn.vue'),
    toolingOffModel: () => import(/* webpackChunkName: "returnEqpDialog" */ './module/toolingOff.vue'),
    changeHistory
  },
  mixins: [mySetting],
  // 数据字典
  data() {
    return {
      UpdateDisabled: true,
      DeleteDisabled: true,
      title: '', // 弹窗标题
      search: {},
      tableLoading: true,
      isDisabled: false, // 是否禁用表单内容
      tableColumns: Object.freeze(
        [
          { prop: '', label: '', type: 'selection' },
          { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
            return (
              <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
            )
          } },
          { prop: 'toolingBarcode', label: this.$t('toolingBarcode'), width: '120px' },
          { prop: 'toolingImage', label: this.$t('toolingImage'), width: '150px', templete: (_scope) => {
            if (_scope.row.toolingImage) {
              return (
                <img src={this.imgUrlFormatter(_scope.row.toolingImage)}
                  style={{ width: '100px', height: '70px' }}/>
              )
            } else {
              return null
            }
          } },
          { prop: 'toolingType', label: this.$t('toolingType'), width: '120px' },
          { prop: 'toolingModel', label: this.$t('toolingModel'), width: '120px' },
          { prop: 'mode', label: this.$t('mode'), templete: (_scope) => {
            return (
              <span>{_scope.row.mode === 1 ? this.$t('machineMode') : this.$t('inventoryModel')}</span>
            )
          } },
          { prop: 'stock', label: this.$t('stock'), width: '120px' },
          { prop: 'flag', label: this.$t('flag'), templete: (_scope) => {
            return (
              <span>{ this.$t(ToolingFlag[_scope.row.flag - 1]) }</span>
            )
          } },
          { prop: 'lifeTime', label: this.$t('lifeTime'), width: '120px' },
          { prop: 'usedTime', label: this.$t('currentTime'), width: '120px' },
          { prop: 'eqpId', label: this.$t('eqpName'), width: '120px' },
          { prop: 'isOnEqp', label: this.$t('computer_status'), width: '100px', templete: (_scope) => {
            return (
              <span>{_scope.row.isOnEqp ? this.$t('yes') : this.$t('no')}</span>
            )
          } },
          { prop: 'siteId', label: 'Head', width: '100px' },
          // { prop: 'siteId', label: this.$t('siteId') },
          { prop: 'owner', label: this.$t('owner'), width: '120px' },
          { prop: 'stockQty', label: this.$t('qty'), width: '100px' },
          { prop: 'lendQty', label: '线上数量', width: '100px' },
          { prop: 'scrapQty', label: '报废数量', width: '100px' },
          { prop: 'allQty', label: '总数', width: '100px' },
          { prop: 'internalBarcode', label: this.$t('internalBarcode'), width: '150px' },
          // { prop: 'handlerTypeStr', label: this.$t('handlerTypeList'), width: '100px' },
          // { prop: 'testerTypeStr', label: this.$t('testerTypeList'), width: '100px' },
          // { prop: 'package', label: this.$t('package'), width: '100px' },
          // { prop: 'mfg', label: this.$t('mfg'), width: '100px' },
          { prop: 'receiveDate', label: this.$t('receiveDate'), width: '120px' },
          { prop: 'releaseDate', label: this.$t('releaseDate'), width: '100px' },
          { prop: 'siteQty', label: this.$t('siteQty'), width: '100px' },
          { prop: 'clientBarcode', label: this.$t('clientBarcode'), width: '100px' },
          { prop: 'nextPMDateStr', label: this.$t('nextPMDate'), width: '150px' },
          // { prop: 'remark', label: this.$t('remark') },
          { prop: '', label: this.$t('modifyHistory'), fixed: 'right', templete: (_scope) => {
            return (
              <el-button type='text' size='small' on-click={() => this.handleViewClick(_scope.row)}>{
                this.$t('updateHis')
              }</el-button>
            )
          } },
          { prop: '', label: this.$t('details'), fixed: 'right', templete: (_scope) => {
            return (
              <el-button type='text' size='small' on-click={() => this.scopedHandle(_scope.row)}>{
                this.$t('details')
              }</el-button>
            )
          } }
        ]
      ),
      headers: {
        Token: getToken()
      },
      ToolingFlag: Object.freeze(
        [
          'Free',
          'Lend',
          'Lock',
          'PM',
          'Occupy', // 占用
          'Repairs', // 报修
          'Defect',
          // 'Engineer',
          'SendBack'
        ]
      )
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    this.initList()
  },
  methods: {
    imgUrlFormatter(url) {
      if (url === '' || url == null || url === undefined) return
      return this.baseApi + '/' + url
    },
    switchHandle(val) {
      switch (val) {
        case 'add':
          this.handleClickAdd()
          break
        case 'del':
          this.handleDel()
          break
        case 'modify':
          this.modify()
          break
        case 'download':
          this.download()
          break
        case 'export':
          this.export()
          break
        default:
          break
      }
    },
    // 新增数据
    handleClickAdd() {
      this.title = this.$t('add')
      this.$refs.myDialog.openDialog()
    },
    // 删除数据
    handleDel() {
      this.$confirm(
        this.$t('confirmDelete') +
          this.multipleSelection.length +
          this.$t('recordCount'),
        this.$t('tip'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      ).then(() => {
        const ids = this.multipleSelection.map((ele) => {
          return ele.id
        })
        crudJob.del({ ids: ids }).then((res) => {
          this.doMerge(res)
          this.setOnePage()
          this.initList()
        })
      })
    },
    // 修改数据
    modify() {
      this.title = this.$t('modify')
      this.isDisabled = false
      this.$refs.myDialog.openDialog(this.multipleSelection[0])
    },
    // 入库
    oprnWareHousing(val, label) {
      this.$refs.wareHousingDialog.openDialog(
        val,
        label,
        this.multipleSelection
      )
    },
    // 借用
    openLend() {
      this.$refs.lendDialog.openDialog()
    },
    // 归还
    returnEqp() {
      this.$refs.returnEqpDialog.openDialog()
    },
    // 维护
    maintain() {
      this.$refs.maintainDialog.openDialog()
    },
    handleViewClick(row) {
      this.$refs.changeHistoryDialog.openDialog('MTMS_TOOLING_INFO', row.id)
    },
    // SendBack
    doSendBack() {
      const ids = this.multipleSelection.map((ele) => ele.id)
      crudJob.toolingSendBack({ ids }).then((res) => {
        // tips({ message: this.$t(res.message), code: res.code })
        this.$betterTips(res, this.initList)
      })
    },
    toolingOn() {
      this.$refs.toolingOnModel.handleOpen()
    },
    toolingOff() {
      this.$refs.toolingOffModel.handleOpen()
    },
    // 切换分页
    getList(val) {
      this.listQuery = val
      this.initList()
    },
    // 初始化列表
    initList() {
      crudJob.getList(this.$clearNull({ ...this.listQuery, ...this.search })).then((res) => {
        this.tableData = res.data
        this.total = res.total
        this.tableLoading = false
      })
    },
    // 点击查询
    doSearch(val) {
      this.search = val
      this.listQuery.page = 1
      this.initList()
    },
    // 查看详情
    scopedHandle(val) {
      this.isDisabled = true
      this.title = this.$t('view')
      this.$refs.myDialog.openDialog(val)
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
    },
    // 关闭弹窗清空数据
    closeDialog() {
      this.isDisabled = false
      // this.initList()
    },
    download() {
      crudJob.download({ name: 'ToolingBaseList' }).then((res) => {
        window.open(this.baseApi + '/' + res.data)
      })
    },
    uploadSuccess(response, file, fileList) {
      // 第{ele.index}行 {this.$t(ele.msgCode)}
      // 第{ele.split(',')[0]}行 {this.$t(ele.split(',')[1])}
      // this.netTips(response.code)
      if (response.code !== 1) {
        const h = this.$createElement
        const listVNode = response.data.map((item) => {
          return (
            <p style={ { width: '240px' }}>
              <span style={ { width: '100%', wordWrap: 'break-word' }}>{item.index ? `第{${item.index}}行` : ''}{this.$t(item.msgCode)}</span>
            </p>
          )
        })
        const styles = {
          color: 'teal',
          overflowX: 'hidden',
          overflowY: 'auto',
          width: '280px',
          maxHeight: 'calc(100vh - 120px)'
        }
        this.$notify({
          message: h('div', { style: styles }, listVNode),
          type: 'error',
          duration: 0
        })
        fileList = []
      } else {
        this.$betterTips(response, this.initList)
      }
    },
    importFail() {
      this.$notify({
        message: this.$t('uploadFail'),
        type: 'error',
        duration: 3500
      })
    },
    export() {
      crudJob.getList(this.$clearNull({ ...this.listQuery, ...this.search, toexcel: 1 })).then((res) => {
        window.open(this.baseApi + '/' + res.data)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/defaultStyle.scss";
.table-buttons-box{
  padding: 0 22px 10px 22px;
  background-color: #fff;
}
.drawer-container{
  height: 100vh;
  overflow-y: auto;
  padding-top: 30px;
}
.upload-btn{
  margin: 0 10px;
}
</style>
